from flask import request
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, PasswordField, SubmitField
from wtforms.validators import DataRequired, EqualTo, Length, ValidationError
from app.models import Admin

''' 登录表单 '''
class LoginForm(FlaskForm):
    username = StringField(validators=[DataRequired('请输入用户名')])
    password = StringField(validators=[DataRequired('请输入密码')])
    # verify_code = StringField(validators=[DataRequired('请输入验证码')])

''' 自定义验证器 '''
class AdminValidate(object):
    def __init__(self, username_field, message=None) -> None:
        self.username_field = username_field
        self.message = message
    
    def __call__(self, form, field):
        username = form[self.username_field].data
        admin_id = request.args.get('id', 0, type=int)
        if not admin_id:
            admin = Admin.query.filter_by(username=username).first()
        else:
            admin = Admin.query.filter(Admin.username==username, Admin.id != admin_id).first()

        if admin:
            raise ValidationError(self.message)
        else:
            return True
        
class AdminForm(FlaskForm):
    role_id = SelectField(label="角色",validators=[DataRequired('请选择角色')], choices=[], coerce=int)
    username = StringField(label="用户名",validators=[DataRequired('请输入用户名'), Length(5, 10, "用户名大于5个字符"), AdminValidate("username", "用户名已经存在")])
    password = PasswordField(label="密码",validators=[DataRequired('请输入密码')])
    rpassword = PasswordField(label="确认密码",validators=[DataRequired('请再次输入密码'), EqualTo('password', '两次输入密码不一致')])
    submit = SubmitField(label="立即保存")

class EditPasswordForm(FlaskForm):
    oldpassword = PasswordField(label="旧密码",validators=[DataRequired('请输入旧密码')])
    password = PasswordField(label="新密码",validators=[DataRequired('请输入新密码')])
    rpassword = PasswordField(label="确认密码",validators=[DataRequired('请再次输入密码'), EqualTo('password', '两次输入密码不一致')])
    submit = SubmitField(label="修改密码")

class MenuForm(FlaskForm):
    name = StringField(label="菜单名称",validators=[DataRequired('请输入菜单名称')])
    url = StringField(label="URL地址",validators=[DataRequired('请输入URL地址')])
    sort = StringField(label="排序")
    submit = SubmitField(label="立即保存")
    
class RoleForm(FlaskForm):
    name = StringField(label="角色名称",validators=[DataRequired('请输入角色名称')])
    submit = SubmitField(label="立即保存")

class LoginForm(FlaskForm):
    username = StringField(label="用户名",validators=[DataRequired('请输入用户名')])
    password = PasswordField(label="密码",validators=[DataRequired('请输入密码')])
    submit = SubmitField(label="立即登录")